package com.luo.partner.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.luo.common.annotation.BaseService;
import com.luo.common.base.BaseServiceImpl;
import com.luo.common.utils.Query;
import com.luo.partner.dao.mapper.TabMonthlyKnotMapper;
import com.luo.partner.dao.mapper.TabUsrsMapper;
import com.luo.partner.dao.mapper.ext.ExtTabUsrsMapper;
import com.luo.partner.dao.model.TabMonthlyKnot;
import com.luo.partner.dao.model.TabRed;
import com.luo.partner.dao.model.TabUsrs;
import com.luo.partner.dao.model.TabUsrsExample;
import com.luo.partner.dao.model.TabUsrsTemp;
import com.luo.partner.service.TabRedRecordService;
import com.luo.partner.service.TabRedService;
import com.luo.partner.service.TabUsrsService;
import com.luo.system.dao.UserDao;
import com.luo.system.domain.UserDO;

/**
* TabUsrsService实现
* Created by laohu on 2018/8/28.
*/
@Service
@Transactional
@BaseService
public class TabUsrsServiceImpl extends BaseServiceImpl<TabUsrsMapper, TabUsrs, TabUsrsExample> implements TabUsrsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TabUsrsServiceImpl.class);

    @Autowired
    TabUsrsMapper tabUsrsMapper;

    @Autowired
    ExtTabUsrsMapper extTabUsrsMapper;
    
    @Autowired
    TabMonthlyKnotMapper tabMonthlyKnotMapper;
    
    @Autowired
    UserDao userMapper;

	@Autowired
    private TabRedService tabRedService;
	
	@Autowired
    private TabRedRecordService tabRedRecordService;

	@Override
	public TabUsrs get(Long id) {
		return tabUsrsMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<TabUsrs> list() {
		return tabUsrsMapper.selectByExample(new TabUsrsExample());
	}

	@Override
	public int save(TabUsrs role) {
		return tabUsrsMapper.insertSelective(role);
	}

	@Override
	public int update(TabUsrs role) {
		return tabUsrsMapper.updateByPrimaryKeySelective(role);
	}
	
	@Override
	@Transactional
	public void recharge(TabUsrs usrs,BigDecimal un_settlement_recharge) throws RuntimeException {
		int i = tabUsrsMapper.updateByPrimaryKeySelective(usrs);
		if (i > 0) {
			List<TabRed> list = tabRedService.findRedList(usrs.getInviteUserId(), un_settlement_recharge);
			if (list != null) {
				for (TabRed tabRed : list) {
					if (tabRed.getSetType() == 1) {
						//1表示按充值金额的百分比
						if (tabRedRecordService.addUserRed(usrs.getUsrsId(), tabRed, un_settlement_recharge) <= 0) {
							throw new RuntimeException("送红包失败");
						}
					}else if (tabRed.getSetType() == 0 && un_settlement_recharge.compareTo(tabRed.getLowerLimit()) >= 0 && un_settlement_recharge.compareTo(tabRed.getUpLimit()) <= 0){
						//0表示按上下限
						if (tabRedRecordService.addUserRed(usrs.getUsrsId(), tabRed, un_settlement_recharge) <= 0) {
							throw new RuntimeException("送红包失败");
						}
					}
				}
			}
		}else {
			throw new RuntimeException("增加用户充值金额失败");
		}
	}

	@Override
	public int remove(Long id) {
		return tabUsrsMapper.deleteByPrimaryKey(id);
	}

	@Override
	public List<TabUsrs> list(Long userId) {
		TabUsrsExample example = new TabUsrsExample();
		example.createCriteria().andUsrsIdEqualTo(userId);
		return tabUsrsMapper.selectByExample(example);
	}
	@Override
	public List<TabUsrs> list(Map<String, Object> map) {
		return tabUsrsMapper.selectByExample(new TabUsrsExample());
	}

	@Override
	public int batchRemove(Long[] ids) {
		return 0;
	}

	@Override
	public int count(Query query) {
		return 0;
	}

	@Override
	public List<TabUsrsTemp> findInviteUserList(Map<String, Object> map) {
		return extTabUsrsMapper.findInviteUserList(map);
	}

	@Override
	public int countInviteUserList(Map<String, Object> map) {
		return extTabUsrsMapper.countInviteUserList(map);
	}

	@Override
	public int findUserByAccount(String account) {
		TabUsrsExample example = new TabUsrsExample();
		TabUsrsExample.Criteria criteria = example.or();
		criteria.andAccountEqualTo(account);
		return tabUsrsMapper.countByExample(example);
	}
	
	@Override
	public int findUserByTel(String tel) {
		TabUsrsExample example = new TabUsrsExample();
		TabUsrsExample.Criteria criteria = example.or();
		criteria.andTelEqualTo(tel);
		return tabUsrsMapper.countByExample(example);
	}

	@Override
	public List<TabUsrs> findUnSettlementRechargeUserList() {
		TabUsrsExample example = new TabUsrsExample();
		example.createCriteria().andUnSettlementRechargeGreaterThan(new BigDecimal(0));
		return tabUsrsMapper.selectByExample(example);
	}
	
	@Override
	@Transactional
	public void settlementRecharge(TabUsrs tabUsrs) throws RuntimeException {

		UserDO userDo = userMapper.get(tabUsrs.getInviteUserId());
		if (userDo == null) {
			throw new RuntimeException("合伙人不存在");
		}
		
		int dbResult = extTabUsrsMapper.updateUserRecharge(tabUsrs.getUsrsId());
		if (dbResult <= 0) {
			throw new RuntimeException("更新用户的结算金额有误");
		}
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		BigDecimal un_withdraw_commission = null;
		try {
			paramMap.put("userId", userDo.getUserId());
			un_withdraw_commission = userDo.getCommissionRate().divide(new BigDecimal(100), BigDecimal.ROUND_HALF_UP).multiply(tabUsrs.getUnSettlementRecharge());
			paramMap.put("un_withdraw_commission", un_withdraw_commission);
		} catch (Exception e) {
			throw e;
		}
		
		dbResult = userMapper.updateCommission(paramMap);
		if (dbResult <= 0) {
			throw new RuntimeException("更新合伙人的佣金金额有误");
		}
		
		// 增加记录
		TabMonthlyKnot record = new TabMonthlyKnot();
		record.setCommission(un_withdraw_commission);
		record.setCreateTime(new Date());
		record.setSettlementRecharge(tabUsrs.getUnSettlementRecharge());
		record.setUserId(userDo.getUserId());
		record.setUsrsId(tabUsrs.getUsrsId());
		dbResult = tabMonthlyKnotMapper.insert(record);
		if (dbResult <= 0) {
			throw new RuntimeException("增加结算记录失败");
		}
		
	}
	
	@Override
	public List<Long> findUsrsIdList(Map<String, Object> params) {
		return extTabUsrsMapper.findUsrsIdList(params);
	}
}